﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace NHibernate.FactoryDAL
{
    /// <summary>
    /// 创建数据层对象
    /// </summary>
    public sealed class DataFactory
    {
        #region CreateObject

        //不使用缓存
        private static object CreateObjectNoCache(string AssemblyPath, string classNamespace)
        {
            try
            {
                object objType = Assembly.Load(AssemblyPath).CreateInstance(classNamespace);
                return objType;
            }
            catch//(System.Exception ex)
            {
                //string str=ex.Message;// 记录错误日志
                return null;
            }

        }
        //使用缓存
        private static object CreateObject(string AssemblyPath, string classNamespace)
        {
            Comm.memcached.MemcachedTools cache = new Comm.memcached.MemcachedTools();
            object objType = cache.Get<object>(classNamespace);
            if (objType == null)
            {
                try
                {
                    objType = Assembly.Load(AssemblyPath).CreateInstance(classNamespace);
                    cache.Add(classNamespace, objType, 0, 10, 0);// 写入缓存
                }
                catch//(System.Exception ex)
                {
                    //string str=ex.Message;// 记录错误日志
                }
            }
            return objType;
        }
        #endregion

        /// <summary>
        /// 创建数据层对象
        /// </summary>
        /// <typeparam name="T">数据层对象类型</typeparam>
        /// <param name="ClassName">类名</param>
        /// <returns></returns>
        public static T Create<T>(string ClassName)
        {
            string ClassNamespace = Comm.Config.AssemblyPath + "." + ClassName;
            object objType = CreateObject(Comm.Config.AssemblyPath, ClassNamespace);
            return (T)objType;
        }
    }
}
